package com.zanfeng.signleplatform.modules.auth.controller;

import com.zanfeng.signleplatform.api.io.modules.auth.AuthFileIO;
import com.zanfeng.signleplatform.api.result.modules.auth.AuthFileResult;
import com.zanfeng.signleplatform.api.result.modules.resourceFile.ResourceFileResult;
import com.zanfeng.signleplatform.api.service.modules.file.FileService;
import com.zanfeng.signleplatform.base.BaseController;
import com.zanfeng.signleplatform.common.baidu.MD5;
import com.zanfeng.signleplatform.results.ApiResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Api(value = "AuthFileController", description = "[后台]后台管理-文件上传")
@RestController
@RequestMapping("/modules/authFile")
public class AuthFileController extends BaseController {

    @Resource
    private FileService fileService;

    private String basePath = "files";
    private String tempPath = System.getProperty("java.io.tmpdir");

    @ApiOperation(value = "上传文件", notes = "上传文件", response = AuthFileResult.class)
    @PostMapping("/uploadFile")
    public ApiResult uploadFile(@RequestParam("file") MultipartFile file) {
        File tempFile = null;
        try {
            AuthFileResult authFileResult = new AuthFileResult();
            String fileUuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = fileUuid + "." + StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            tempFile = new File(tempPath + File.separator + fileName);
            file.transferTo(tempFile);
            String fileMd5 = MD5.md5(tempFile);
            ResourceFileResult resourceFileResult = fileService.findResourceFileResultByMd5(fileMd5);
            if (resourceFileResult == null) {
                //  首次上传，先保存文件到指定文件目录，再插入数据库文件表
                File targetFile = new File(basePath + File.separator + fileName);
                FileUtils.copyFile(tempFile, targetFile);
                resourceFileResult = new ResourceFileResult();
                resourceFileResult.setLenght(tempFile.length());
                resourceFileResult.setMd5(fileMd5);
                resourceFileResult.setName(file.getOriginalFilename());
                resourceFileResult.setUrl(fileName);
                resourceFileResult.setUuid(fileUuid);
                fileService.saveResourceFile(resourceFileResult);
            }
            //  已经上传过，直接从数据库文件表读取相关信息
            authFileResult.setFileMd5(resourceFileResult.getMd5());
            authFileResult.setFileUrl(resourceFileResult.getUrl());
            authFileResult.setFileName(file.getOriginalFilename());
            return ApiResult.success(authFileResult);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ApiResult.fail("上传失败");
        } finally {
            if (tempFile != null) {
                try {
                    FileUtils.forceDelete(tempFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperation(value = "检查文件", notes = "检查文件", response = AuthFileResult.class)
    @PostMapping("/checkFile")
    public ApiResult checkFile(@RequestBody @Valid AuthFileIO io) {
        ResourceFileResult resourceFileResult = fileService.findResourceFileResultByMd5(io.getFileMd5());
        if (resourceFileResult != null) {
            //  已经上传过，直接从数据库文件表读取相关信息
            AuthFileResult authFileResult = new AuthFileResult();
            authFileResult.setFileMd5(resourceFileResult.getMd5());
            authFileResult.setFileUrl(resourceFileResult.getUrl());
            authFileResult.setFileName(resourceFileResult.getName());
            return ApiResult.success(authFileResult);
        }
        return ApiResult.success();
    }

    @ApiOperation(value = "检查文件", notes = "检查文件，使用逗号分隔md5", response = AuthFileResult.class)
    @PostMapping("/checkFiles")
    public ApiResult checkFiles(@RequestBody @Valid AuthFileIO io) {
        List<ResourceFileResult> fileResultList = fileService.queryResourceFileResultListByMd5s(io.getFileMd5());
        if (CollectionUtils.isNotEmpty(fileResultList)) {
            //  已经上传过，直接从数据库文件表读取相关信息
            List<AuthFileResult> resultList = new ArrayList<>();
            for (ResourceFileResult resourceFileResult : fileResultList) {
                AuthFileResult authFileResult = new AuthFileResult();
                authFileResult.setFileMd5(resourceFileResult.getMd5());
                authFileResult.setFileUrl(resourceFileResult.getUrl());
                authFileResult.setFileName(resourceFileResult.getName());
                resultList.add(authFileResult);
            }
            return ApiResult.success(resultList);
        }
        return ApiResult.success();
    }

}
